import React, { ReactElement, useEffect, useState } from 'react';
import codePush, {
  RemotePackage,
  DownloadProgress,
  LocalPackage
} from 'react-native-code-push';
import { View, Text } from 'react-native';

import styles from './style';
import ScheduleLine from '../ScheduleLine';
import { modalOpen } from '../../util/global';
import PortraitAlert from '../Alert/PortraitAlert';
import { APP_BLUE } from '../../constant/color';

interface UpdateProgress {
  update: RemotePackage;
  packageSize: number;
  download: () => void;
}

const TIME = 30 * 1000;

export default ({
  update,
  packageSize,
  download
}: UpdateProgress): ReactElement => {
  const [percentage, setPercentage] = useState(0);

  const reDownload = (): void => {
    modalOpen({
      Type: (): React.ReactElement => (
        <PortraitAlert
          title="软件更新失败"
          subTitle="更新过程遇到网络错误，请检查网络后重试。"
          sureDesc="立即重试"
          sureAction={download}
        />
      ),
      needBack: true
    });
  };

  useEffect((): (() => void) => {
    let timer: NodeJS.Timer | null;
    const clearTimer = (): void => {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
    };
    update
      .download((progress: DownloadProgress): void => {
        setPercentage((progress.receivedBytes / progress.totalBytes) * 100);
        clearTimer();
        timer = setTimeout((): void => {
          clearTimer();
          reDownload();
        }, TIME);
      })
      .then((localPackage: LocalPackage): void => {
        clearTimer();
        modalOpen({
          Type: (): React.ReactElement => (
            <PortraitAlert
              title="更新完毕"
              sureDesc="立即重启"
              subTitle={`更新包大小共${(packageSize / 1024 / 1024).toFixed(
                2
              )}MB，已更新100%\n重启App，即可体验新版本啦`}
              sureAction={(): void => {
                localPackage.install(codePush.InstallMode.IMMEDIATE);
              }}
            />
          ),
          needBack: true
        });
      })
      .catch((e): void => {
        clearTimer();
        reDownload();
      });
    return (): void => {
      clearTimer();
    };
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>软件更新中</Text>
      <ScheduleLine
        width={168}
        wrapperStyle={styles.wrapper}
        progressStyle={styles.progress}
        percentage={percentage}
        processColor={[APP_BLUE, APP_BLUE]}
      />
      <Text style={styles.desc}>
        更新包大小共{(packageSize / 1024 / 1024).toFixed(2)}MB，已更新
        {Math.floor(percentage)}%
      </Text>
    </View>
  );
};
